//页面初始化操作
$(function(){
    //生成产品编码
    let code = randomString(6);
    $("#memberProductCode").val(code);

    uploadImg();
    // 产品有效期--配置
    $('#productPeriodValidity').daterangepicker({
        timePicker: true,
        startDate: moment().startOf('hour'),
        endDate: moment().startOf('hour').add(24, 'hour'),
        locale: {
            format: 'YYYY-MM-DD HH:mm',
            cancelLabel: '清空',
        },
        timePicker24Hour : true,
        autoUpdateInput: false,
    });
    $('#productPeriodValidity').on('apply.daterangepicker', function(ev, picker) {
        $(this).val(picker.startDate.format('YYYY-MM-DD HH:mm') + ' 至 ' + picker.endDate.format('YYYY-MM-DD HH:mm'));
    });
    $('#productPeriodValidity').on('cancel.daterangepicker', function(ev, picker) {
        $(this).val('');
    });
});

/**
 * 新增会员产品--提交
 */
function addMemberProduct(){
    var memberCardName = $("#memberCardName").val();//会员卡名称
    var memberProductCode = $("#memberProductCode").val();//会员产品编码
    var sellingCardPrice = $("#sellingCardPrice").val();//售卡价格
    var productPeriodValidity = $('#productPeriodValidity').val().split(" 至 ");//产品有效期
    var whetherIncludedAchievement = $("input:radio[name='whetherIncludedAchievement']:checked").val();
    var serviceNumber = $("#serviceNumber").val();//会员服务总次数
    var membershipLevel = $("#membershipLevel").val();//会员等级
    var performanceConversionRatio = $('#performanceConversionRatio').val();//业绩金额比
    var whetherRenew = $("input:radio[name='whetherRenew']:checked").val();//是否可续费产品
    //获取选择文件
    var file = document.getElementById("customerPic").files[0];


    if(!memberCardName){
        promptInfo("会员卡名称不能为空!");
        return;
    }

    if(!memberProductCode){
        promptInfo("会员产品编码不能为空!");
        return;
    }

    if(!sellingCardPrice){
        promptInfo("售卡价格不能为空!");
        return;
    }

    var productPeriodValidityStart = "";
    var productPeriodValidityEnd = "";
    if(productPeriodValidity.length > 1){
        productPeriodValidityStart = productPeriodValidity[0];
        productPeriodValidityEnd = productPeriodValidity[1];
    }else{
        promptInfo("产品有效期不能为空!");
        return;
    }

    if(!whetherIncludedAchievement){
        promptInfo("请选择是否计入会员产品业绩!");
        return;
    }

    if(!serviceNumber){
        promptInfo("会员服务总次数不能为空!");
        return;
    }

    if(!membershipLevel){
        promptInfo("会员等级不能为空!");
        return;
    }


    if(!performanceConversionRatio){
        promptInfo("业绩金额比不能为空!");
        return;
    }

    if(performanceConversionRatio < 0 || performanceConversionRatio > 1){
        promptInfo("业绩金额比请输入0-1的数字!");
        return;
    }

    //新增会员产品JSON数据
    var productJsonData = {
        "memberCardName":memberCardName,//会员卡名称
        "memberProductCode":memberProductCode,//会员产品编码
        "sellingCardPrice":sellingCardPrice,//售卡价格
        "productPeriodValidityStart":productPeriodValidityStart,//会员产品有效期起始时间
        "productPeriodValidityEnd":productPeriodValidityEnd,//会员产品有效期截止时间
        "whetherIncludedAchievement":whetherIncludedAchievement,//是否计入会员产品业绩
        "whetherRenew":whetherRenew,//是否可续费产品
        "serviceNumber" : serviceNumber,//会员服务总次数
        "membershipLevel" : membershipLevel,//会员等级
        "performanceConversionRatio":performanceConversionRatio,//业绩换算比例
        "file" : file
    };

    $.ajax({
        url: '/customerMemberProduct/addCustomerMemberProduct',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(productJsonData),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '保存成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("赠品列表", "/front/productManager/memberProductForm");

                                // 提交完表单，重新加载相关table列表页面
                                refreshActivePane('/front/productManager/memberProductForm');
                                delStorageAndRemove(navTab);
                            }
                        }
                    }
                });
            } else if(data.code == 'MP0001'){
                //会员卡名称重复
                $.alert(data.message);
            }else if(data.code == 'MP0002'){
                //会员产品编码重复
                $.alert(data.message);
            }
        }),
        error: (function (res) {
            $.alert("保存失败");
        })
    })
}

/**
 * 新增会员产品--取消
 */
function cancelAddMemberProduct(){
    $('form')[0].reset();
}

/**
 * 消息提示弹出框
 * @param content  ---提示内容
 */
function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}

/**
 * 上传图片
 * */
function uploadImg() {
    $(document).on('click', '.file-browser', function () {
        var file = $(this).closest('.file-group').find('[type="file"]');
        file.on('click', function (e) {
            e.stopPropagation();
        });
        file.trigger('click');
    });

    $(document).on('change', '.file-group [type="file"]', function () {
        var $this = $(this);
        var $input = $(this)[0];
        var $len = $input.files.length;
        //var formFile = new FormData();
        if ($len == 0) {
            $input.nextElementSibling.value = '';
            $input.nextElementSibling.nextElementSibling.innerHTML = '';

        } else {
            var fileAccaccept = $this.attr('accaccept');
            var fileType = $input.files[0].type;
            var type = (fileType.substr(fileType.lastIndexOf("/") + 1)).toLowerCase();

            if (!type || fileAccaccept.indexOf(type) == -1) {
                lightyear.notify('您上传图片的类型不符合(' + fileAccaccept + ')', 'danger', 1500);
                $input.value = '';
                if ($input.nextElementSibling.value == '') {
                    $input.nextElementSibling.nextElementSibling.innerHTML = '';
                }

            } else {
                $input.nextElementSibling.value = '';
                var str = "<img src='" + getObjectURL(document.getElementById("customerPic").files[0]) + "'/>";
                //将图片动态添加到图片展示区
                document.getElementById("customerImgBox").innerHTML = str;
            }
        }
    });
}

//获取图片路径方法
function getObjectURL(file) {
    var url = null ;
    if (window.createObjectURL!=undefined) { // basic
        url = window.createObjectURL(file) ;
    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;
    } else if (window.webkitURL!=undefined) { // webkit or chrome
        url = window.webkitURL.createObjectURL(file) ;
    }
    return url ;
}

/**
 * 生成随机码
 * @param len
 * @returns {string}
 */
function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}